<template>
  <Page class="bg-[#f5f7fa] min-h-screen">
    <!-- 顶部背景 -->
    <view
      class="fixed top-0 left-0 w-full z-[3] h-[220rpx] bg-gradient-to-b from-[#4CAF50] to-[#81C784]"
    ></view>

    <!-- 吸顶标题栏 -->
    <view class="sticky top-0 z-30 w-full box-border pt-[32rpx] pb-[16rpx] bg-transparent">
      <PageHeader title="" :showBack="true" :onlyBack="true" @back="handleBack" />
      <view class="text-[36rpx] w-full text-center font-bold text-white">
        报名详情
      </view>
    </view>

    <!-- 报名状态卡片 -->
    <view class="px-[32rpx] mt-[20rpx]">
      <view class="bg-white rounded-[20rpx] shadow-sm p-[24rpx] relative overflow-hidden">
        <!-- 状态标签 -->
        <view 
          class="absolute top-0 right-0 px-[30rpx] py-[8rpx] text-[26rpx] font-bold text-white"
          :class="applicationInfo.statusBgClass"
        >
          {{ applicationInfo.status }}
        </view>
        
        <!-- 任务标题 -->
        <view class="text-[30rpx] font-bold text-[#333] mb-[16rpx]">
          {{ taskInfo.title }}
        </view>
        
        <!-- 核心信息 -->
        <view class="grid grid-cols-2 gap-[20rpx] mb-[24rpx]">
          <view class="flex flex-col">
            <text class="text-[22rpx] text-[#999] mb-[4rpx]">报名时间</text>
            <text class="text-[26rpx] text-[#555]">{{ applicationInfo.applyTime }}</text>
          </view>
          <view class="flex flex-col">
            <text class="text-[22rpx] text-[#999] mb-[4rpx]">最新更新</text>
            <text class="text-[26rpx] text-[#555]">{{ applicationInfo.updateTime }}</text>
          </view>
          <view class="flex flex-col" v-if="showSalary">
            <text class="text-[22rpx] text-[#999] mb-[4rpx]">薪资/报酬</text>
            <text class="text-[26rpx] text-[#ff7d00] font-medium">{{ taskInfo.salary }}</text>
          </view>
          <view class="flex flex-col" v-if="showDeadline">
            <text class="text-[22rpx] text-[#999] mb-[4rpx]">截止时间</text>
            <text class="text-[26rpx] text-[#555]">{{ taskInfo.deadline }}</text>
          </view>
        </view>
        
        <!-- 操作按钮组 -->
        <view class="flex gap-[16rpx]" v-if="showActionButtons">
          <nut-button 
            size="small" 
            type="default" 
            class="flex-1 border-[#ff4d4f] text-[#ff4d4f] bg-transparent"
            @click="handleCancelApplication"
            v-if="canCancel"
          >
            取消报名
          </nut-button>
          <nut-button 
            size="small" 
            type="success" 
            class="flex-1"
            @click="handleContactPublisher"
          >
            联系发布方
          </nut-button>
        </view>
      </view>
    </view>

    <!-- 任务详情 -->
    <view class="px-[32rpx] mt-[20rpx]">
      <view class="bg-white rounded-[20rpx] shadow-sm p-[24rpx]">
        <view class="text-[28rpx] font-bold text-[#333] mb-[16rpx] flex items-center">
          <IconFont name="task-detail" size="28" class="mr-[10rpx] text-[#4CAF50]" />
          任务详情
        </view>
        
        <!-- 发布方信息 -->
        <view class="flex items-center gap-[16rpx] mb-[20rpx] p-[16rpx] bg-[#f9f9f9] rounded-[16rpx]">
          <view class="w-[60rpx] h-[60rpx] rounded-full overflow-hidden">
            <img :src="taskInfo.publisherAvatar" alt="发布方头像" class="w-full h-full object-cover" />
          </view>
          <view class="flex-1">
            <view class="text-[26rpx] font-medium text-[#333]">{{ taskInfo.publisherName }}</view>
            <view class="text-[22rpx] text-[#999]">{{ taskInfo.publisherType === 'company' ? '企业认证' : '个人发布' }}</view>
          </view>
          <view class="text-[24rpx] text-[#666] flex items-center">
            <IconFont name="trust" size="22" class="mr-[6rpx] text-[#faad14]" />
            可信度 {{ taskInfo.trustScore }}%
          </view>
        </view>
        
        <!-- 任务描述 -->
        <view class="mb-[24rpx]">
          <view class="text-[24rpx] text-[#999] mb-[8rpx]">任务描述</view>
          <view class="text-[26rpx] text-[#555] whitespace-pre-line leading-[1.6]">
            {{ taskInfo.description }}
          </view>
        </view>
        
        <!-- 其他信息（标签） -->
        <view class="flex flex-wrap gap-[12rpx]">
          <view v-for="(tag, index) in taskInfo.tags" :key="index" class="px-[16rpx] py-[6rpx] bg-[#f1f8e9] text-[#52c41a] text-[22rpx] rounded-full">
            {{ tag }}
          </view>
        </view>
      </view>
    </view>

    <!-- 流程进度 -->
    <view class="px-[32rpx] mt-[20rpx]" v-if="progressSteps.length > 0">
      <view class="bg-white rounded-[20rpx] shadow-sm p-[24rpx]">
        <view class="text-[28rpx] font-bold text-[#333] mb-[20rpx] flex items-center">
          <IconFont name="progress" size="28" class="mr-[10rpx] text-[#4CAF50]" />
          报名进度
        </view>
        
        <view class="relative">
          <!-- 进度线 -->
          <view class="absolute left-[20rpx] top-0 bottom-0 w-[2rpx] bg-[#e0e0e0]"></view>
          
          <!-- 进度步骤 -->
          <view class="space-y-[30rpx]">
            <view v-for="(step, index) in progressSteps" :key="index" class="flex items-start">
              <!-- 步骤点 -->
              <view class="w-[40rpx] h-[40rpx] rounded-full z-10 flex items-center justify-center flex-shrink-0 mt-[2rpx]">
                <view 
                  class="w-[20rpx] h-[20rpx] rounded-full"
                  :class="step.completed ? 'bg-[#4CAF50]' : 'bg-[#e0e0e0]'"
                ></view>
              </view>
              
              <!-- 步骤内容 -->
              <view class="ml-[20rpx] flex-1">
                <view class="flex justify-between items-center mb-[4rpx]">
                  <view class="text-[26rpx] font-medium" :class="step.completed ? 'text-[#4CAF50]' : 'text-[#333]'">
                    {{ step.title }}
                  </view>
                  <view class="text-[22rpx] text-[#999]">{{ step.time }}</view>
                </view>
                <view class="text-[24rpx] text-[#666] mt-[4rpx]">
                  {{ step.desc }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 沟通记录 -->
    <view class="px-[32rpx] mt-[20rpx] mb-[30rpx]">
      <view class="bg-white rounded-[20rpx] shadow-sm p-[24rpx]">
        <view class="text-[28rpx] font-bold text-[#333] mb-[20rpx] flex items-center">
          <IconFont name="message" size="28" class="mr-[10rpx] text-[#4CAF50]" />
          沟通记录
        </view>
        
        <!-- 空状态 -->
        <view v-if="messages.length === 0" class="py-[40rpx] text-center">
          <IconFont name="no-message" size="60" class="text-[#e0e0e0] mb-[16rpx]" />
          <view class="text-[24rpx] text-[#999]">暂无沟通记录，点击"联系发布方"开始对话</view>
        </view>
        
        <!-- 消息列表 -->
        <view class="space-y-[24rpx]" v-else>
          <view v-for="(msg, index) in messages" :key="index" class="flex">
            <!-- 对方消息 -->
            <view v-if="!msg.isMe" class="flex items-start gap-[12rpx]">
              <view class="w-[50rpx] h-[50rpx] rounded-full overflow-hidden flex-shrink-0">
                <img :src="taskInfo.publisherAvatar" alt="对方头像" class="w-full h-full object-cover" />
              </view>
              <view class="max-w-[70%]">
                <view class="bg-[#f0f0f0] p-[16rpx] rounded-tl-none rounded-tr-[12rpx] rounded-bl-[12rpx] rounded-br-[12rpx] text-[24rpx] text-[#333]">
                  {{ msg.content }}
                </view>
                <view class="text-[20rpx] text-[#999] mt-[4rpx] ml-[10rpx]">
                  {{ msg.time }}
                </view>
              </view>
            </view>
            
            <!-- 我的消息 -->
            <view v-if="msg.isMe" class="flex items-start justify-end gap-[12rpx] ml-auto">
              <view class="max-w-[70%] text-right">
                <view class="bg-[#81C784] p-[16rpx] rounded-tl-[12rpx] rounded-tr-none rounded-bl-[12rpx] rounded-br-[12rpx] text-[24rpx] text-white">
                  {{ msg.content }}
                </view>
                <view class="text-[20rpx] text-[#999] mt-[4rpx] mr-[10rpx]">
                  {{ msg.time }}
                </view>
              </view>
              <view class="w-[50rpx] h-[50rpx] rounded-full overflow-hidden flex-shrink-0">
                <img src="/static/images/my-avatar.png" alt="我的头像" class="w-full h-full object-cover" />
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </Page>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { Button as nutButton } from "@nutui/nutui-taro";
import { get } from "@/utils/request";

// 接收路由参数
const routerParams = Taro.getCurrentInstance().router.params;
const { applicationId, type } = routerParams;

// 报名信息
const applicationInfo = ref({
  status: "", // 报名状态：待审核/已通过/已拒绝/已完成
  statusBgClass: "", // 状态背景样式
  applyTime: "", // 报名时间
  updateTime: "" // 最后更新时间
});

// 任务信息
const taskInfo = ref({
  title: "",
  publisherName: "",
  publisherAvatar: "",
  publisherType: "company", // company/person
  trustScore: 98,
  salary: "",
  deadline: "",
  description: "",
  tags: []
});

// 进度步骤
const progressSteps = ref([
  // 示例：[{ title: "已报名", completed: true, time: "06-15 09:30", desc: "您已成功报名该任务" }]
]);

// 沟通记录
const messages = ref([
  // 示例：[{ content: "请问该任务需要自带工具吗？", isMe: true, time: "06-15 10:20" }]
]);

// 计算是否显示薪资（日结/悬赏/招聘显示，签到任务可能不显示）
const showSalary = computed(() => {
  return ["daily", "reward", "recruit", "factory"].includes(type);
});

// 计算是否显示截止时间
const showDeadline = computed(() => {
  return !["completed", "rejected"].includes(applicationInfo.value.status);
});

// 计算是否显示操作按钮
const showActionButtons = computed(() => {
  return !["已拒绝", "已完成"].includes(applicationInfo.value.status);
});

// 计算是否可取消报名
const canCancel = computed(() => {
  return ["待审核", "已通过"].includes(applicationInfo.value.status);
});

// 获取报名详情数据
const getApplicationDetail = async () => {
  try {
    const res = await get(`/enroll/detail?id=${applicationId}&type=${type}`);
    if (res.code === 200) {
      const data = res.data;
      
      // 报名信息
      applicationInfo.value = {
        ...data.application,
        // 根据状态设置背景样式
        statusBgClass: getStatusBgClass(data.application.status)
      };
      
      // 任务信息
      taskInfo.value = data.task;
      
      // 进度步骤
      progressSteps.value = data.progressSteps;
      
      // 沟通记录
      messages.value = data.messages || [];
    }
  } catch (err) {
    console.error("获取报名详情失败：", err);
    Taro.showToast({ title: "加载失败", icon: "none" });
  }
};

// 根据状态获取背景样式
const getStatusBgClass = (status) => {
  const classMap = {
    "待审核": "bg-[#faad14]",
    "已通过": "bg-[#4CAF50]",
    "已拒绝": "bg-[#ff4d4f]",
    "已完成": "bg-[#1890ff]"
  };
  return classMap[status] || "bg-[#8c8c8c]";
};

// 取消报名
const handleCancelApplication = () => {
  Taro.showModal({
    title: "确认取消",
    content: "取消报名后将无法参与该任务，是否确认？",
    success: async (res) => {
      if (res.confirm) {
        try {
          const res = await post("/enroll/cancel", {
            id: applicationId,
            type
          });
          if (res.code === 200) {
            Taro.showToast({ title: "已取消报名", icon: "success" });
            // 跳转回我的报名列表
            setTimeout(() => {
              Taro.navigateBack({ delta: 1 });
            }, 1500);
          }
        } catch (err) {
          Taro.showToast({ title: "取消失败", icon: "none" });
        }
      }
    }
  });
};

// 联系发布方
const handleContactPublisher = () => {
  Taro.navigateTo({
    url: `/pages/chat/index?targetId=${taskInfo.value.publisherId}&type=${taskInfo.value.publisherType}`
  });
};

// 返回上一页
const handleBack = () => {
  Taro.navigateBack();
};
</script>